<template>
  <div class="app-container">
    <!-- 盘库 -->

    <el-row :gutter="24">
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <!-- 搜索 -->
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="盘库单号" prop="code">
              <el-input
                v-noSpace
                v-model="queryParams.code"
                placeholder="请输入盘库单号"
                class="!w-[192px]"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
              <el-button
                icon="plus"
                v-hasPerm="'sys:movingWork:edit'"
                type="warning"
                @click="handleEdit({}, 'add')"
              >
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="never">
          <el-table v-loading="loading" :data="pageData" @row-click="handleRowClick">
            <el-table-column prop="code" label="盘库单号" align="center" />
            <el-table-column prop="name" label="盘库任务名称" align="center" />
            <el-table-column prop="checkDate" label="盘库日期" align="center" />
            <!-- <el-table-column prop="stockNum" label="数量" align="center" /> -->
            <el-table-column prop="checkNum" label="盘点数量" align="center" />
            <el-table-column prop="status" label="盘库状态" align="center">
              <template #default="scope">
                {{ formatStatus(scope.row.status) }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
            <el-table-column label="操作" fixed="right" width="170" align="center">
              <template #default="scope">
                <div v-if="scope.row.status != 2">
                  <el-button
                    type="primary"
                    link
                    size="small"
                    @click.stop="handleEdit(scope.row, 'edit')"
                    v-hasPerm="'sys:movingWork:edit'"
                  >
                    修改
                  </el-button>
                  <el-button
                    type="danger"
                    v-hasPerm="'sys:movingWork:del'"
                    size="small"
                    link
                    @click="handleDel(scope.row)"
                  >
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
        <el-card v-if="rowObj" shadow="never" class="mt20">
          <el-table ref="sonTable" :data="copySonTableData">
            <el-table-column prop="code" label="物料编号" align="center" />
            <el-table-column prop="productName" label="物料名称" align="center" />
            <el-table-column prop="stockNum" label="数量" align="center">
              <template #default="scope">
                {{ scope.row.stockNum || 0 }}
                {{ unitFormat(scope.row.unit) }}
              </template>
            </el-table-column>
            <el-table-column prop="checkNum" label="盘点数量" align="center">
              <template #default="scope">
                {{ scope.row.checkNum || 0 }}
                {{ unitFormat(scope.row.unit) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="盘库状态" align="center">
              <template #default="scope">
                {{ formatStatus(scope.row.status) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 删除 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogParams"
        v-loading="loading"
        :inline="true"
        label-width="150px"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="盘库任务名称" prop="name">
              <el-input
                v-noSpace
                v-model="dialogParams.name"
                placeholder="请输入盘库任务名称"
                clearable
                style="width: 100%"
                maxlength="100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘库日期" prop="checkDate">
              <el-date-picker
                v-model="dialogParams.checkDate"
                type="date"
                placeholder="选择时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                clearable
              />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="数量（kg）" prop="stockNum">
              <el-input-number v-model="dialogParams.stockNum" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘点数量（kg）" prop="checkNum">
              <el-input-number v-model="dialogParams.checkNum" placeholder="请输入" />
            </el-form-item>
          </el-col> -->

          <!-- <el-col :span="12">
            <el-form-item label="盘库状态" prop="status">
              <el-select
                v-model="dialogParams.status"
                placeholder="请选择状态"
                style="width: 190px"
              >
                <el-option label="待盘库" :value="0" />
                <el-option label="盘库中" :value="1" />
                <el-option label="已完成" :value="2" />
              </el-select>
            </el-form-item>
          </el-col> -->

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-noSpace
                v-model="dialogParams.remark"
                placeholder="请输入备注"
                clearable
                type="textarea"
                :rows="4"
                style="width: 550px"
                maxlength="500"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item label="原材料名称" prop="name">
          <el-select v-model="value1" multiple placeholder="请选择原材料" style="width: 200px">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label + ' - ' + item.kg"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item label="产品名称" prop="name">
          <el-select v-model="value1" multiple placeholder="请选择产品名称" style="width: 200px">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label + ' - ' + item.kg"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
      </el-form>

      <el-divider />

      <h3>产品列表</h3>
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >
        全选
      </el-checkbox>
      <el-checkbox-group v-model="selectedProducts" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="(item, index) in productTableData" :key="index" :value="item">
          {{ item.productName }}
        </el-checkbox>
      </el-checkbox-group>

      <h3>原材料列表</h3>
      <el-checkbox
        v-model="checkAlls"
        :indeterminate="isIndeterminates"
        @change="handleCheckAllChanges"
      >
        全选
      </el-checkbox>
      <el-checkbox-group v-model="selectedRaws" @change="handleCheckedCitiesChanges">
        <el-checkbox v-for="(item, index) in rawTableData" :key="index" :value="item">
          {{ item.productName }}
        </el-checkbox>
      </el-checkbox-group>

      <el-row class="mt20 mb20">
        <el-col :span="18" />
        <el-col :span="4">
          <el-button type="primary" @click="pushSonTableData">选择后添加子级列表</el-button>
        </el-col>
      </el-row>

      <el-table ref="sonTable" :data="sonTableData" style="width: 100%; height: 200px">
        <el-table-column prop="code" label="物料编号" align="center" />
        <el-table-column prop="productName" label="物料名称" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleDeleteRow(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button v-debounce="submit" type="primary">提 交</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import movingWorkAPI, {
  movingWorkPageQuery,
  movingWorkPageVO,
} from "@/api/warehouseManage/movingWork";
import configApi, { ConfigType } from "@/api/config/config";
import productBomAPI from "@/api/productBom/productBom";
import { FormItemRule } from "element-plus/es";
import { ref } from "vue";

defineOptions({
  name: "User",
  inheritAttrs: false,
});
const checkAll = ref(false);
const isIndeterminate = ref(false);
const checkAlls = ref(false);
const isIndeterminates = ref(false);
const queryFormRef = ref(ElForm);
const selectedProducts = ref<string[]>([]);
const selectedRaws = ref<string[]>([]);
const sonTableData = ref<{ code?: string; productName?: string; id?: number }[]>([]);
const copySonTableData = ref<{ id?: number }[]>([]);
const value1 = ref([]);
const rowObj = ref({});
const options = [
  {
    value: "Option1",
    label: "Option1",
    kg: "1kg",
  },
  {
    value: "Option2",
    label: "Option2",
    kg: "2kg",
  },
  {
    value: "Option3",
    label: "Option3",
    kg: "3kg",
  },
  {
    value: "Option4",
    label: "Option4",
    kg: "4kg",
  },
  {
    value: "Option5",
    label: "Option5",
    kg: "5kg",
  },
];

const dialogFormRef = ref(ElForm);

const dialogParams = reactive({
  name: "",
  checkDate: "",
  stockNum: 0,
  checkNum: 0,
  status: "",
  remark: "",
});

const rules = reactive<Record<string, FormItemRule[]>>({
  name: [{ required: true, message: "盘库任务名称是必填项", trigger: "blur" }],
  checkDate: [{ required: true, message: "盘库日期是必填项", trigger: "blur" }],
});

const queryParams = reactive<movingWorkPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const dialog = reactive({
  visible: false,
  title: "",
  type: "",
});

const statusOptions = [
  { value: "completed", label: "完成" },
  { value: "in_progress", label: "盘库中" },
  { value: "not_started", label: "未开始" },
];

const pageData = ref<movingWorkPageVO[]>();
// 定义产品和原材料的数据类型
interface Product {
  code?: string;
  productName: string;
}
const productTableData = ref<Product[]>([]);
const rawTableData = ref<Product[]>([]);
const total = ref(0);
const listTotal = ref(0);
const loading = ref(false);

//产品列表 potato carrot beef
const productList = ref<
  {
    codeName: string;
    codeValue: string;
  }[]
>([]);
const getProductName = () => {
  configApi.getConfigListByType(ConfigType.PROD_CODE).then((res) => {
    productList.value = res;
  });
};

// 查询
function handleQuery() {
  console.log("queryParams", queryParams);
  sonTableData.value = [];
  rowObj.value = false;
  movingWorkAPI
    .getPage(queryParams)
    .then((data) => {
      pageData.value = [...(data?.list as any)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
// 合计
function handleTotal() {
  loading.value = true;
  console.log("queryParams", queryParams);
  movingWorkAPI
    .getTotal(queryParams)
    .then((data) => {
      console.log("data", data);
      listTotal.value = data?.qtyTotal ?? 0;
      // pageData.value = [...(data?.list as any)];
      // total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  // queryParams.deptId = undefined;
  // queryParams.createTime = undefined;
  handleQuery();
}

function handleEdit(row: any, type: string) {
  console.log("row", row);
  dialog.visible = true;
  selectedProducts.value = [];
  selectedRaws.value = [];
  sonTableData.value = [];

  dialog.type = type;
  if (type == "add") {
    dialog.title = "新增";
  } else {
    dialog.title = "修改";
    handleRowClick(row);
    Object.assign(dialogParams, row);
  }
}

// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);

const unitFormat = (unit: any) => {
  let unitLabel = unitOptions.value.find((item) => item.value === unit)?.label;
  return unitLabel;
};
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};

const getProductList = async (type: any) => {
  try {
    const response = await productBomAPI.getTypePage({
      pageNum: 1,
      pageSize: 999,
      productType: type,
    });
    const dataList = response?.list || [];
    if (type == "1") {
      productTableData.value = dataList.map((item: any) => ({
        code: item.code ?? "", // 确保有 code 属性
        productName: item.productName ?? "", // 确保有 productName 属性
      })) as Product[];
    } else {
      rawTableData.value = dataList.map((item: any) => ({
        code: item.code ?? "", // 确保有 code 属性
        productName: item.productName ?? "", // 确保有 productName 属性
      })) as Product[];
    }
  } catch (error) {
    console.error("Error fetching product types:", error);
  }
};
function handleDel(row: any) {
  ElMessageBox.confirm("确定要删除该盘库任务吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      movingWorkAPI
        .delRowList({ id: row?.id })
        .then(() => {
          ElMessage.success("删除成功");
          handleQuery(); // 重新查询数据列表
        })
        .catch((error) => {
          // ElMessage.error(`删除失败: ${error}`);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
}

function handleCloseDialog() {
  dialog.visible = false;
  clearDialogFormData();
}

// 提交弹窗
function submit() {
  dialogFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    if (!sonTableData.value?.length) {
      return ElMessage.error("请选择产品或原材料");
    }
    let paramsData = <any>{};
    if (dialog.title == "新增") {
      paramsData = {
        status: "0",
        name: dialogParams.name,
        checkDate: dialogParams.checkDate,
        remark: dialogParams.remark,
        stockCheckDetailList: sonTableData.value.map((item: any) => ({
          productCode: item.code,
          productName: item.productName,
        })),
      };
    } else {
      sonTableData.value.forEach((item) => {
        let data = copySonTableData.value.find((res: any) => res.productCode === item.code);
        if (data) {
          item.id = data.id;
        }
      });
      paramsData = {
        ...dialogParams,
        stockCheckDetailList: sonTableData.value.map((item: any) => ({
          id: item?.id,
          productCode: item.code,
          productName: item.productName,
        })),
      };
    }
    loading.value = true;
    movingWorkAPI
      .submitDialog(paramsData)
      .then((data) => {
        dialog.visible = false;
        // loading.value = false;
        if (dialog.title == "新增") {
          ElMessage.success("新增成功");
          handleQuery();
        } else {
          ElMessage.success("修改成功");
          handleRowClick(paramsData);
        }

        // handleQuery();
        clearDialogFormData();
      })
      .catch((err) => {
        ElMessage.error(`${err}`);
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

//重置弹窗
function clearDialogFormData() {
  let data = {
    name: "",
    checkDate: "",
    remark: "",
  };
  sonTableData.value = [];

  Object.assign(dialogParams, { ...data });
}

function formatStatus(cellValue: any) {
  console.log(cellValue);
  switch (cellValue) {
    case 0:
      return "待盘库";
    case 1:
      return "盘库中";
    case 2:
      return "已完成";
    default:
      return "未知状态";
  }
}

const handleProductSelectionChange = (selection: any) => {
  selectedProducts.value = selection;
};
const handleRawSelectionChange = (selection: any) => {
  selectedRaws.value = selection;
};

function pushSonTableData() {
  // sonTableData.value = [];
  if (!selectedProducts.value?.length && !selectedRaws.value?.length) {
    return ElMessage.warning("请选择要添加的数据");
  }

  let list = JSON.parse(JSON.stringify([...selectedProducts.value, ...selectedRaws.value]));

  const resault = [...new Set(list.map((item: any) => item.code))].map((code) => {
    return list.find((item: any) => item.code === code);
  });
  sonTableData.value = [...resault] as any;
  console.log(sonTableData);
  console.log(selectedProducts);
  console.log(selectedRaws);

  ElMessage.success("添加成功");
  // selectedProducts.value = [];
  // selectedRaws.value = [];
}
// 删除行的方法
const handleDeleteRow = (index: number, row: any) => {
  sonTableData.value.splice(index, 1);
  console.log(selectedProducts.value);
  console.log(selectedRaws.value);
  const selectedProductsIndex = selectedProducts.value.findIndex(
    (item: any) => item.code == row.code
  );
  console.log(selectedProductsIndex);
  if (selectedProductsIndex !== -1) {
    selectedProducts.value.splice(selectedProductsIndex, 1); // 删除索引为 index 的元素
  }
  const selectedRawsIndex = selectedRaws.value.findIndex((item: any) => item.code == row.code);
  console.log(selectedRawsIndex);
  if (selectedRawsIndex !== -1) {
    selectedRaws.value.splice(selectedRawsIndex, 1); // 删除索引为 index 的元素
  }
};

// 修改 handleRowClick 方法中的赋值逻辑，确保类型一致
function handleRowClick(row: any) {
  console.log("row", row);
  rowObj.value = { ...row };
  movingWorkAPI
    .getRowList({
      parentCode: row.code,
    })
    .then((response) => {
      console.log("object", response);
      if (Array.isArray(response)) {
        sonTableData.value = response.map((item: any) => ({
          code: item.productCode ?? "",
          productName: item.productName ?? "",
        }));
        copySonTableData.value = JSON.parse(JSON.stringify(response));
        console.log(sonTableData);
        console.log(productTableData);
        console.log(rawTableData);

        sonTableData.value.forEach((row: any) => {
          console.log(row);
          const selectedProductsIndex = productTableData.value.findIndex(
            (item: any) => item.code == row.code
          );
          console.log(selectedProductsIndex);

          if (selectedProductsIndex !== -1) {
            nextTick(() => {
              isIndeterminate.value = true;
              selectedProducts.value.push(row);
            });
          }
          const selectedRawsIndex = rawTableData.value.findIndex(
            (item: any) => item.code == row.code
          );
          if (selectedRawsIndex !== -1) {
            // selectedRaws.value.push(row);
            nextTick(() => {
              isIndeterminates.value = true;
              selectedRaws.value.push(row);
            });
          }
          console.log(selectedRawsIndex);
        });
        console.log(selectedProducts);
        console.log(selectedRaws);
      }
    })
    .catch((error) => {
      //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {});
}
const handleCheckAllChange = (val: any) => {
  selectedProducts.value = val ? [...(productTableData.value as any)] : [];
  isIndeterminate.value = false;
};
const handleCheckedCitiesChange = (value: any) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === productTableData.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < productTableData.value.length;
};
const handleCheckAllChanges = (val: any) => {
  selectedRaws.value = val ? [...(rawTableData.value as any)] : [];
  isIndeterminates.value = false;
};
const handleCheckedCitiesChanges = (value: any) => {
  const checkedCount = value.length;
  checkAlls.value = checkedCount === rawTableData.value.length;
  isIndeterminates.value = checkedCount > 0 && checkedCount < rawTableData.value.length;
};
onMounted(() => {
  handleQuery();
  getProductList("1");
  getProductList("2");
  getUnitList();
  // handleTotal();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
</style>
